require 'lib'
require 'event_editor/commands/condition'

module EventEditor
  class CommandsDialog
   def self.show(base, model, edit_command, &func)
      if edit_command.empty?
        @dialog = Gtk::Dialog.new("Commands",
               base,
               Gtk::Dialog::MODAL,
               nil,
               ["Cancel", Gtk::Dialog::RESPONSE_CANCEL]
               )
        @dialog.window_position = Gtk::Window::POS_MOUSE
        @func = func
        @model = model

        @edit_command = edit_command
        @buttons = []
        @group = nil
        # init components
        @dialog.vbox.add(self.create_panel)
        @dialog.vbox.show_all
        @dialog.set_size_request(300, 300)
        
        # run
        @dialog.run do |response|
          if response == Gtk::Dialog::RESPONSE_CANCEL
            @dialog.destroy
          end
        end
      else
        case edit_command[0]
          when 'if'
            Commands::Condition.show(base, model, edit_command, {:static => false}, &func)
          else
            Lib.fileNameToClass('event_editor/commands/','EventEditor::Commands::',edit_command[0]).show(base, model, edit_command, {}, &func)
        end
      end
    end
    
    def self.add_button(parent, name, command, &func)
      b = Gtk::Button.new(name)
      
      unless command
        b.sensitive = false
        parent.add(b)
        return
      end
      
      b.signal_connect('clicked') do
        func.call if func
      end
      parent.add(b)
    end
  
    def self.create_panel(&func)
      notebook = Gtk::Notebook.new
      
      i = 0
      
      box = nil
      vbox = nil
      
      Dir::glob($res.tool_path + "event_editor/commands/*").each do |path|
        p path
        if (i % 40) == 0
          box = Gtk::HBox.new(true, 8)
          box.set_border_width(5)
          notebook.append_page(box)
        end
        if (i % 8) == 0
          vbox = Gtk::VBox.new(true, 2)
          box.add(vbox)
        end
        if File.file?(path)
          n = File.basename(path).split(".")[0]
          self.add_button(vbox, n, n) do
            Lib.fileNameToClass('event_editor/commands/','EventEditor::Commands::',n).show(@dialog, @model, @edit_command) do |command|
              @func.call(command)
              @dialog.destroy
            end
          end
          
          i += 1
          
        end
      end
      

      
      return notebook
    end
    
  end
end